<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" ref="queryForm" :form="queryForm">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="用户名">
              <a-input v-decorator="['username',{ rules: [{ required: false}] }]" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="状态">
              <a-select placeholder="请选择" v-decorator="['statusEnable',{ rules: [{ required: false}] }]">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="0">禁用</a-select-option>
                <a-select-option value="1">正常</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="昵称">
                <a-input v-decorator="['nickName',{ rules: [{ required: false}] }]"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleSearchReset">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" v-action:ums_umsAdmin_add icon="plus" @click="handleAdd">新建</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" v-action:ums_umsAdmin_delete @click="handleBatchDelete"><a-icon type="delete" />删除</a-menu-item>
          <!-- lock | unlock -->
          <a-menu-item key="2"><a-icon type="lock" />扩展</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- 列表  -->
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="{ show: true, clear: true }"
      :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
    >
      <template v-for="(col, index) in columns" v-if="col.scopedSlots" :slot="col.dataIndex" slot-scope="text">
        <div :key="index">
          <template>{{ text }}</template>
        </div>
      </template>
      <template slot="status" slot-scope="text">
        <div v-if="text==1">正常</div>
        <div v-if="text==0">禁用</div>
      </template>
      <span slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item>
              <a href="javascript:;">详情</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" v-if="record.statusEnable==1" @click="handleDisableStatus(record)">禁用</a>
              <a href="javascript:;" v-if="record.statusEnable==0" @click="handleDisableStatus(record)">启用</a>
            </a-menu-item>
            <a-menu-item>
              <a href="javascript:;" @click="handleDelete(record)">删除</a>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>
    <!--   编辑表单 -->
    <a-modal
      title="操作"
      :width="800"
      v-model="modelVisible"
      :confirmLoading="confirmLoading"
      @ok="handleSaveOrUpdate"
    >
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="ID"
          hasFeedback
          validateStatus="success"
        >
          <a-input
            v-decorator="[ 'adminId',{ rules: [{ required: false }] }]"
            disabled="disabled" />
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="用户名"
          hasFeedback
        >
          <a-input
            v-decorator="[ 'username',{ rules: [{ required: true, message: '请输入用户名!' }] }]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="昵称"
          hasFeedback
        >
          <a-input
            v-decorator="['nickName',{ rules: [{ required: true, message: '请输入用昵称!' }] }]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态"
        >
          <a-select
            v-decorator="['statusEnable',{ rules: [{ required: true, message: '请选择状态!' }] }]"
            placeholder="请选择状态"
          >
            <a-select-option :value="1">正常</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注"
          hasFeedback
        >
          <a-textarea
            v-decorator="['note',{ rules: [{ required: false, message: '' }] },]"
            :rows="5">
          </a-textarea>
        </a-form-item>
        <a-divider />
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import { STable } from '@/components'
import AdminForm from '@/views/common-list/AdminForm'
import api from '@/api'
import { deleteUmsAdmin, updateUmsAdmin, addUmsAdmin, batchDeleteUmsAdmin } from '@/api/umsAdminApi'

export default {
  name: 'TableList',
  components: {
    STable,
    AdminForm
  },
  data () {
    return {
      description: '',
      editModelVisible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this, { name: 'entity_form' }),
      queryForm: this.$form.createForm(this, { name: 'query_form' }),
      editRecord: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
      },
      // 表头
      columns: [
        {
          title: '用户名',
          dataIndex: 'username',
          sorter: true,
          width: 120
        },
        {
          title: '昵称',
          dataIndex: 'nickName',
          scopedSlots: { customRender: 'nickName' }
        },
        {
          title: '备注信息',
          dataIndex: 'note',
          needTotal: false,
          scopedSlots: { customRender: 'note' }
          // customRender: (text) => text + ' 次'
        },
        {
          title: '状态',
          dataIndex: 'statusEnable',
          width: '100px',
          needTotal: false,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: '200px',
          sorter: true,
          scopedSlots: { customRender: 'createTime' }
        },
        {
          table: '操作',
          dataIndex: 'action',
          width: '130px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return this.$http.get(api.umsAdminUrl, {
          params: Object.assign(parameter, this.queryParam)
        }).then(res => {
          return res.data
        })
      },

      selectedRowKeys: [],
      selectedRows: []
    }
  },
  methods: {
    // 搜索查询
    handleSearch () {
      this.queryParam = this.queryForm.getFieldsValue()
      this.loadData = parameter => {
        return this.$http.get(api.umsAdminUrl, {
          params: Object.assign(parameter, this.queryParam)
        }).then(res => {
          return res.data
        })
      }
      this.$refs.table.refresh()
    },
    // 搜索重置
    handleSearchReset () {
      this.queryForm.resetFields()
    },
    handleChange (value, key, column, record) {
      record[column.dataIndex] = value
    },
    handleEdit (record) {
      this.editRecord = Object.assign({}, record)
      this.modelVisible = true
      this.$nextTick(() => {
        let values = this.form.getFieldsValue()
        for(let key in values) {
          values[key] = this.editRecord[key];
          this.form.setFieldsValue(values)
        }
      })
    },
    // 新增
    handleAdd () {
      this.editRecord = {}
      this.modelVisible = true
      this.form.resetFields();
    },
    // 批量删除
    handleBatchDelete () {
      // console.log('===============handleBatchDelete', this.selectedRowKeys)
      // console.log('===============handleBatchDelete', this.selectedRowKeys[0])
      let ids = this.selectedRowKeys
      let params = this.selectedRowKeys
      const that = this
      this.$confirm({
        title: '警告',
        content: `真的要批量删除 ${ids.length} 个吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          // 在这里调用删除接口
          return new Promise((resolve, reject) => {
            batchDeleteUmsAdmin(params)
              .then(res => {
                that.$refs.table.clearSelected()
                that.$refs.table.refresh()
                that.$notification['success']({
                  message: '提示',
                  description: res.msg || '删除成功',
                  duration: 8
                })
                resolve()
              }).catch((err) => {
              reject(err)
              that.$notification['error']({
                message: '提示',
                description: err.msg || '删除失败',
                duration: 8
              })
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    edit (row) {
      row.editable = true
      // row = Object.assign({}, row)
    },
    // eslint-disable-next-line
    handleDelete (row) {
      const that = this
      this.$confirm({
        title: '警告',
        content: `真的要删除 ${row.username} 吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          // 在这里调用删除接口
          return new Promise((resolve, reject) => {
            deleteUmsAdmin(row.adminId)
              .then(res => {
                that.$refs.table.refresh()
                that.$notification['success']({
                  message: '提示',
                  description: res.msg || '删除成功',
                  duration: 8
                })
                resolve()
              }).catch((err) => {
              reject(err)
              that.$notification['error']({
                message: '提示',
                description: err.msg || '删除失败',
                duration: 8
              })
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    handleDisableStatus (row) {
      const that = this
      let txt = row.statusEnable === 1 ? '禁用' : '启用'
      this.$confirm({
        title: '警告',
        content: `真的要${txt} ${row.username} 吗?`,
        okText: txt,
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          // 在这里调用更新接口
          return new Promise((resolve, reject) => {
            let params = { 'adminId': row.adminId,
              'statusEnable': row.statusEnable === 1 ? 0 : 1 }
            updateUmsAdmin(row.adminId, params)
              .then(res => {
                that.$refs.table.refresh()
                that.$notification['success']({
                  message: '提示',
                  description: res.msg || '操作成功',
                  duration: 8
                })
                resolve()
              }).catch((err) => {
              reject(err)
              that.$notification['error']({
                message: '提示',
                description: err.msg || '操作失败',
                duration: 8
              })
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    // 更新、保存
    handleSaveOrUpdate () {
      console.log('model data', this.editRecord)
      // this.confirmLoading = true;
      this.form.validateFields((err, values) => {
        if (err) {
          // this.confirmLoading = false;
          return;
        }
        console.log('Received values of form: ', values);
        this.editRecord = values
        this.confirmLoading = true;
        if (this.editRecord.adminId) {
          // 更新操作
          updateUmsAdmin(this.editRecord.adminId, this.editRecord)
            .then(res => {
              this.$notification['success']({
                message: '提示',
                description: res.msg || '操作成功',
                duration: 8
              })
              this.form.resetFields();
              this.modelVisible = false;
              this.confirmLoading = false;
              this.$refs.table.refresh()
            })
            .catch((err) => {
              this.confirmLoading = false;
              this.$notification['error']({
                message: '提示',
                description: err.msg || '操作失败',
                duration: 8
              })
            })
        }else {
          // 新增操作
          addUmsAdmin(this.editRecord)
            .then(res => {
              this.$notification['success']({
                message: '提示',
                description: res.msg || '操作成功',
                duration: 8
              })
              this.form.resetFields();
              this.modelVisible = false;
              this.confirmLoading = false;
              this.$refs.table.refresh()
            })
            .catch((err) => {
              this.confirmLoading = false;
              this.$notification['error']({
                message: '提示',
                description: err.msg || '操作失败',
                duration: 8
              })
          })
        }
      });
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    }
  }
}
</script>

<style lang="less" scoped>
  .search {
    margin-bottom: 54px;
  }

  .fold {
    width: calc(100% - 216px);
    display: inline-block
  }

  .operator {
    margin-bottom: 18px;
  }

  @media screen and (max-width: 900px) {
    .fold {
      width: 100%;
    }
  }
</style>
